<template>
  <div>
    <el-card shadow="never" class="border-0">
      <!-- 搜索 -->
      <SearchForm :model="searchForm" @search="getList" @reset="resetSearchForm">
        <SearchItem label="">

          <div class="mt-4" style="width: 100%;margin-left: 0px !important;">
            <el-input v-model="searchForm.title" placeholder="媒体名称" class="input-with-select">
              <template #prepend>
                <el-button :icon="Search" />
              </template>
            </el-input>
          </div>
        </SearchItem>
      </SearchForm>


      <!-- 新增|刷新 -->
      <ListHeader layout="create,refresh" @create="handleCreate" @refresh="getList"
        @delete="handleMultiDelete" />

      <el-table ref="multipleTableRef" :data="tableData" stripe v-loading="loading"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="title" label="套餐名称" width="200" />
        <el-table-column prop="limit_count" label="限制条数" width="200" />
        <el-table-column label="包含平台" width="300" align="center">
          <template #default="scope">
            <div class="flex items-center" v-for="(item) in scope.row.platefrom">
              <el-avatar :size="40" :src="item.icon">
                <img src="/empty.png" />

              </el-avatar>
              <div class="ml-3">
                <h6>{{ item.name }}</h6>
                <small>ID:{{ item.en_name }}</small>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="内容类型" width="300" align="center">
          <template #default="scope">
            <div class="flex items-center" v-for="(item) in scope.row.content_type_list">
              <div class="ml-3">
                <small>{{ item.label }}</small>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="order" label="排序" />
        <el-table-column label="激活状态">
          <template #default="{ row }">
            <el-switch :modelValue="row.status" :active-value="true" :inactive-value="false"
              @change="hanledStatus($event, row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <el-button @click="handleEdit(scope.row)" text type="primary" class="p-1">
              <el-icon class="el-icon--left" :size="16">
                <Edit />
              </el-icon>修改
            </el-button>

            <el-popconfirm title="是否要删除该记录？" confirmButtonText="确认" cancelButtonText="取消"
              @confirm="handleDelete(scope.row.id)">
              <template #reference>
                <el-button text type="danger" class="p-1">
                  <el-icon class="el-icon--left" :size="16">
                    <Delete />
                  </el-icon>删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <div class="flex items-center justify-center mt-5">
        <el-pagination background layout="prev, pager ,next" :total="total" :current-page="currentPage"
          :page-size="pageSize" @current-change="getList" />
      </div>
      <!-- 新增|编辑 -->
      <FormDrawer destroyOnClose ref="formDrawerRef" :title="drawerTitle" @submit="selfhandleSubmit">
        <el-form :model="form" ref="formRef" :rules="rules" label-width="80px" :inline="false">
          <el-form-item label="套餐名称" prop="title">
            <el-input v-model="form.title" placeholder="套餐名称" class="input-width" />
          </el-form-item>
          <!-- <el-form-item label="标签" prop="labels">
            <el-input v-model="form.labels" placeholder="标签" class="input-width" />
          </el-form-item> -->

          <el-form-item label="内容类型" prop="content_type">
            <el-select v-model="form.content_type" placeholder="选择所属内容类型" multiple clearable filterable
              class="input-width">
              <el-option v-for="i in contentType" :key="i.value" :label="i.label" :value="i.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="分发平台" prop="platform">
            <el-select v-model="form.platefrom" placeholder="选择所属分发平台" multiple clearable filterable
              class="input-width">
              <el-option v-for="item in platfromList" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="单条价格" prop="item_price">
            <el-input type="number" v-model="form.item_price" placeholder="单条价格" class="input-width" />
          </el-form-item>
          <el-form-item label="可用条数" prop="limit_count">
            <el-input v-model="form.limit_count" placeholder="限制条数" class="input-width" />
          </el-form-item>

          <el-form-item label="折扣率" prop="item_price">
            <el-input type="number" @blur="setTotalPrice" v-model="form.discount" class="input-width"
              placeholder="套餐折扣率">
              <template #append>%</template>
            </el-input>
          </el-form-item>
          <el-form-item label="总价格" prop="price">
            <el-input v-model="form.price" placeholder="套餐价格" class="input-width" />
          </el-form-item>


          <el-form-item label="状态" prop="status">
            <el-switch v-model="form.status" :active-value="true" :inactive-value="false" />
          </el-form-item>
        </el-form>
      </FormDrawer>
    </el-card>
  </div>
</template>
<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import ListHeader from "~/components/ListHeader.vue";
import FormDrawer from "~/components/FormDrawer.vue";
import TagInput from "~/components/TagInput.vue";
import SearchForm from "~/components/SearchForm.vue"
import SearchItem from "~/components/SearchItem.vue"
import { Search } from '@element-plus/icons-vue'

import { useInitTable, useInitForm } from "~/composables/useCommon";

import { getSkusList, postSkus, putSkus, deleteSkus, patchSkusStatus } from "~/api/platefrom/skus"
import { getPlatefromAll } from '~/api/platefrom/index'

// 公共方法
import { getContentType } from "~/composables/util"


import { useStore } from "vuex";
import { formatDateFun, showModal, showPrompt } from "~/composables/util";
import { toast } from "~/composables/util";
const store = useStore();
const { formatDate } = formatDateFun();
const content_type = ref([]);
const list = ref([]);
const platform = ref([]);
const {
  searchForm,
  resetSearchForm,
  tableData,
  loading,
  currentPage,
  total,
  pageSize,
  getList,
  handleDelete,
  hanledStatus,
  multipleTableRef,
  handleSelectionChange,
  handleMultiDelete,
} = useInitTable({
  searchForm: { search: "", title: "", content_type: "", labels: "" },
  requestListAPI: getSkusList,
  delete: deleteSkus,
  updateStatus: patchSkusStatus,
  // pageSize: store.state.pageSize.SkusList,
  pageSize: 10,
  onGetListSuccess: (res) => {
    tableData.value = res.data;

    res.data.forEach(item => {
      let new_content_type = []
      if (item.content_type_ids) {
        let temp_content_type_ids = item.content_type_ids.split(",")
        temp_content_type_ids.forEach(content_type_id => {

          let item_conten_type = contentType.find((o) => {
            return o.value == content_type_id
          })
          new_content_type.push(item_conten_type)
        })
        item.content_type_list = new_content_type
      }
    })


    list.value = res.data
    total.value = res.count;
  },
});

const showSearch = ref(false);

const {
  formDrawerRef,
  formRef,
  form,
  rules,
  editId,
  drawerTitle,
  handleSubmit,
  resetForm,
  handleCreate,
  handleEdit,
} = useInitForm({
  getList,
  create: postSkus,
  update: putSkus,

  form: {
    title: "",
    type: "",
    labels: "",
    content_type: "",
    platefrom: [],
    status: true,
    price: 0,
    item_price: "",
    discount: '',
    limit_count: 0,
  },
  rules: {
    title: [
      {
        required: true,
        message: "套餐名称不能为空",
        trigger: "blur",
      },
    ],
    price: [
      {
        required: true,
        message: "价格不能为空",
        trigger: "blur",
      },
    ],
    limit_count: [
      {
        required: true,
        message: "套餐限制条数不能为空",
        trigger: "blur",
      },
    ],
    platefrom: [
      {
        required: true,
        message: "请选择平台",
        trigger: "blur",
      },
    ],
  },
});

const contentType = getContentType()


const platfromList = ref([])
onMounted(() => {
  // 获取平台信息
  getPlatefromAll({}).then((res) => {
    platfromList.value = res.data
  })
})


const selfhandleSubmit = () => {
  if (form.platefrom.length > 0) {
    form.platefrom_ids = form.platefrom.join(",")
  }
  if (form.content_type.length > 0) {
    form.content_type_ids = form.content_type.join(",")
  }
  handleSubmit()
}

// 设置总价格
const setTotalPrice = () => {
  if (form.discount && form.limit_count && form.item_price) {
    form.price = form.item_price * form.limit_count * form.discount / 100
  } else {
    form.price = form.item_price * form.limit_count
  }
}
</script>
